<script lang="ts" setup>
import Whx from '@/assets/img/whx.jpg'
import {onMounted, ref} from "vue";
import type {BuyMember, MemberInfo} from "@/type/member.ts";
import {useMemberStore} from "@/stores/member.ts";
import {ElMessage, ElMessageBox} from "element-plus";
import type {AddConsumption, PersonalConsumption} from "@/type/consumption.ts";
import {addAConsumption, getConsumptionById} from "@/api/consumption";
import {buyMember} from "@/api/member";

const memberStore = useMemberStore()

const memberInfo = ref<MemberInfo>()

const DialogVisible = ref(false)
const radioValue = ref('30')

// 获取会员信息
const getMemberInformation = async () => {
  try {
    const memberId = memberStore.memberInfo.memberId
    if (memberId !== -1) {
      const info = await memberStore.getMemberInfo(memberId)
      if (info instanceof Error) {
        ElMessage.error(info.message)
      } else {
        memberInfo.value = info
      }
    } else {
      ElMessage.error("错误数据，请稍后重试")
    }
  } catch (e) {
    ElMessage.error((e as Error).message)
  }
}

// 开通（续费）会员
const openMembership = () => {
  radioValue.value = '30'
  DialogVisible.value = true
}
const confirm = () => {
  ElMessageBox.confirm(
      '确定要购买此套餐?',
      '再次确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
  )
      .then(async () => {
        try {
          const consumption: AddConsumption = {
            memberId: memberStore.memberInfo.memberId,
            consumptionType: '会员',
            amount: Number(radioValue.value),
            relatedId: -1
          }
          console.log(memberInfo.value)
          const updateInfo: BuyMember = {
            memberId: memberStore.memberInfo.memberId,
            membershipStartDate: memberInfo.value?.membershipStartDate || null,
            membershipEndDate: memberInfo.value?.membershipEndDate || null,
            days: Number(radioValue.value),
          }
          console.log(updateInfo)
          const consumptionResult = await addAConsumption(consumption)
          const updateResult = await buyMember(updateInfo)
          if (consumptionResult.code === 1 && updateResult.code === 1) {
            ElMessage({
              type: 'success',
              message: '购买成功',
            });
            await getMemberInformation() // 刷新列表
            await getConsumption()
            DialogVisible.value = false
          } else {
            // 处理错误情况
            ElMessage({
              type: 'error',
              message: consumptionResult.message || updateResult.message || '删除失败，请稍后重试。',
            });
          }
        } catch (error) {
          // 捕获网络请求或其他异常
          ElMessage({
            type: 'error',
            message: '删除失败，请检查网络或稍后重试。',
          });
        }
      })
      .catch(() => {
        // 用户取消删除操作
        ElMessage({
          type: 'info',
          message: '购买取消',
        });
      });
}

// 表格数据
const parentBorder = ref(false)
const tableData = ref<PersonalConsumption[]>([{
  // 默认数据
  consumptionType: "123",
  amount: 100,
  consumptionDate: "weizhi",
}])
const getConsumption = async () => {
  const result = await getConsumptionById(memberStore.memberInfo.memberId)
  if (result.code == 1) {
    tableData.value = result.data
  }
}
onMounted(() => {
  getMemberInformation()
  getConsumption()
})
</script>

<template>
  <!-- 主内容区 -->
  <div class="member-center-container">
    <div class="member-info">
      <el-card class="info-card">
        <el-row>
          <el-col :span="8">
            <el-avatar :size="150" :src="memberInfo?.avatar || Whx"/>
          </el-col>
          <el-col :span="8">
            <el-descriptions
                :column="2"
                direction="vertical"
                size="default"
                title="基本信息"
            >
              <el-descriptions-item label="姓名">{{ memberInfo?.memberName }}</el-descriptions-item>
              <el-descriptions-item label="用户名">{{ memberInfo?.username }}</el-descriptions-item>
              <el-descriptions-item label="开通时间">{{
                  memberInfo?.membershipStartDate || '从未开通'
                }}
              </el-descriptions-item>
              <el-descriptions-item label="到期时间">{{
                  memberInfo?.membershipEndDate || '从未开通'
                }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="8">
            <el-descriptions
                :column="2"
                direction="vertical"
                size="default"
                title="权益"
            >
              <el-descriptions-item label="身份">{{ memberInfo?.memberType }}</el-descriptions-item>
              <el-descriptions-item label="基本" label-align="left" width="140">使用大量健身设备、购买优质健身课程
              </el-descriptions-item>
            </el-descriptions>
            <el-button type="primary" @click="openMembership">开通（续费）会员</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <div class="consumption-records">
      <el-table :border="parentBorder" :data="tableData" class="consumption-records-table" max-height="445"
                table-layout="fixed">
        <!--表格展示-->
        <el-table-column align="center" label="消费类型" prop="consumptionType" width="150px"/>
        <el-table-column align="center" label="金额" prop="amount" width="150px"/>
        <el-table-column align="center" label="消费日期" prop="consumptionDate"/>
      </el-table>
    </div>
  </div>
  <!-- 购买会员Dialog -->
  <div class="open-membership-dialog">
    <el-dialog
        v-model="DialogVisible"
        :show-close="false"
        align-center
        class="membership"
        title="开通（续费）会员"
        width="500px"
    >
      <p style="margin: 10px">请选择套餐</p>
      <el-radio-group v-model="radioValue" size="large">
        <el-radio-button label="30￥/月" value="30"/>
        <el-radio-button label="90￥/3月" value="90"/>
        <el-radio-button label="180￥/6月" value="180"/>
        <el-radio-button label="360￥/年" value="360"/>
      </el-radio-group>
      <template #footer>
        <el-button type="primary" @click="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.member-center-container {
  height: 100vh;
  width: 100%;
  background-color: rgb(245, 247, 250);

  .member-info {
    height: 220px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .info-card {
      height: 90%;
      width: 60%;

      .el-col {
        display: flex;
        justify-content: center;
        //align-items: center;
        flex-direction: column;
      }
    }
  }

  .consumption-records {
    //height: calc(100vh - 100px);
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .consumption-records-table {
      height: 90%;
      width: 60%;
      border-radius: 5px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
    }
  }
}

.open-membership-dialog {
  .membership {
    display: flex;
    justify-content: center;
    //align-items: center;
    flex-direction: column;
  }
}
</style>